
package us.hornerscorners.lollipop.inject;

/*
 * #%L
 * LollipopRouter
 * %%
 * Copyright (C) 2013 - 2014 Jim Horner
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */

import java.io.InputStream;

import javax.enterprise.context.ApplicationScoped;

import javax.enterprise.inject.Alternative;
import javax.enterprise.inject.Produces;

import org.yaml.snakeyaml.TypeDescription;
import org.yaml.snakeyaml.Yaml;

import org.yaml.snakeyaml.constructor.Constructor;

import us.hornerscorners.lollipop.config.LollipopConfig;
import us.hornerscorners.lollipop.config.RoutingConfig;


/**
 * Class description
 *
 *
 * @version        v1.0, 2014-09-07
 * @author         Jim Horner
 */
@Alternative
public class LollipopConfigProducer {

    /**
     * Method description
     *
     *
     * @param is
     *
     * @return
     */
    public static LollipopConfig createConfig(InputStream is) {

        Constructor c = new Constructor();
        TypeDescription listenerDescription = new TypeDescription(LollipopConfig.class);

        listenerDescription.putListPropertyType("routings", RoutingConfig.class);
        c.addTypeDescription(listenerDescription);

        Yaml yaml = new Yaml(c);
        LollipopConfig result = null;

        try {

            result = yaml.loadAs(is, LollipopConfig.class);

        } catch (Exception e) {

            throw new IllegalStateException("Unable to read LollipopConfig.yml", e);
        }

        return result;
    }

    /**
     * Method description
     *
     *
     * @return
     */
    @Produces
    @ApplicationScoped
    public LollipopConfig createConfig() {

        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        InputStream is = cl.getResourceAsStream("META-INF/LollipopConfig.yml");

        if (is == null) {

            String msg = "Missing META-INF/LollipopConfig.yml";

            throw new IllegalStateException(msg);
        }

        return createConfig(is);
    }
}
